package model.threads;

import model.environmentConfig.*;

import java.io.*;
import java.net.*;
import java.util.Calendar;

public class ListenerServer extends Thread {
	private ServerSocket server;
	private int currentPort;
	private long lastComm;
	private PrintWriter out;
	private BufferedReader in;
	private String nodeNum;
	private int foo=0;
	private Socket socket;
	
	public ListenerServer(int currentPort, String nodeNum){
		this.currentPort=currentPort;
		this.nodeNum=nodeNum;
		lastComm=Calendar.getInstance().getTimeInMillis();
	}
	
	public void run(){
		socket=null;
		
		try{
			server=new ServerSocket(currentPort);
			System.out.println(server);
			
			while(true){
				socket=server.accept();
				System.out.println("Server has connected!");
				System.out.println(socket);
				lastComm=Calendar.getInstance().getTimeInMillis();
				
				out = new PrintWriter(socket.getOutputStream(), true);
				in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
				
				while(!socket.isClosed()){
					Thread.sleep(CommunicationChannel.TIME_OUT/2);
					String msg="seven"+(foo++);
					System.out.println("Sending: "+msg);
					out.println(msg);
					while(!in.ready()){
						if(Calendar.getInstance().getTimeInMillis()-lastComm>CommunicationChannel.TIME_OUT){
							socket.close();
							break;
						}
					}
					if(!socket.isClosed()){
						System.out.println("Recieved: "+in.readLine());
						lastComm=Calendar.getInstance().getTimeInMillis();
					}
				}
				
				System.out.println("Connection lost!\n");
			}
		}
		catch(IOException ioe){
			System.out.println(ioe.getMessage());
			System.out.print("Whoops! It didn't work!\n");
		}
		catch(InterruptedException ie){
			System.out.println("\nSomething thread like went wrong!\n");
		}
	}
	
	public Socket getSocket(){
		return(socket);
	}
	
	public long lastConnection(){
		return(lastComm);
	}
	
	@Override
	public void interrupt(){
		try{
			server.close();
		}
		catch(IOException ioe){
			
		}
		super.interrupt();
	}
}
